package com.dfbz.demo;

import com.cloud.item.ItemApplication;
import com.cloud.item.entity.Order;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
@SpringBootTest(classes = ItemApplication.class)
@RunWith(SpringRunner.class)
public class Demo01_RestTemplate {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * get请求
     */
    @Test
    public void test1() {

        // 直接获取响应体
//        Map resultMap = restTemplate.getForObject("http://localhost:9001/order/1", Map.class);

        // 获取响应实体
        ResponseEntity<Map> entity = restTemplate.getForEntity("http://localhost:9001/order/1", Map.class);

        // 响应码
        System.out.println(entity.getStatusCodeValue());

        // 响应头
        System.out.println(entity.getHeaders());

        // 响应体
        Map resultMap = entity.getBody();
        System.out.println(resultMap);
    }

    /**
     * post请求
     */
    @Test
    public void test2() {
        Map resultMap = restTemplate.postForObject(
                "http://localhost:9001/order",
                new Order(1, "赣南脐橙", 48.8, 10),
                Map.class);

        // 响应码
        System.out.println(resultMap);
    }

    /**
     * put请求
     */
    @Test
    public void test3() {

        // 可以发送put请求,但是没有返回值
        restTemplate.put(
                "http://localhost:9001/order/11",
                new Order(null, "赣南脐橙", 48.8, 10));

        // 封装一个请求对象
        HttpEntity<Order> httpEntity=new HttpEntity(new Order(null, "赣南脐橙", 48.8, 10));

        // 发送PUT请求
        ResponseEntity<Map> responseEntity = restTemplate.exchange(
                "http://localhost:9001/order/110",
                HttpMethod.PUT,
                httpEntity,
                Map.class
        );

        Map resultMap = responseEntity.getBody();
        System.out.println(resultMap);

    }

    /**
     * delete请求
     */
    @Test
    public void test4() {
        // 可以发送put请求,但是没有返回值
//        restTemplate.delete("http://localhost:9001/order/110");

        // 发送PUT请求
        ResponseEntity<Map> responseEntity = restTemplate.exchange(
                "http://localhost:9001/order/110",
                HttpMethod.DELETE,
                null,
                Map.class
        );

        Map resultMap = responseEntity.getBody();
        System.out.println(resultMap);
    }
}
